package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.AttrLenthConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.InstockErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PaymentErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BomErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.FundsSetErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.SheetAssembleEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import com.xbongbong.saas.enums.business.PaymentSheetDistributorEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.FundUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;
import static java.lang.String.format;

public class SaveFormatHelp {

    private static final Logger LOG = LoggerFactory.getLogger(SaveFormatHelp.class);

    /**
     * 其他收入单、其他支出单公用的save处理部分：校验金额，时间等
     * @param validateDataDTO 数据对象
     * @param data 数据data
     * @param sheetTypeEnum 类型总枚举
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public static void otherBeforeSave(ValidateDataDTO validateDataDTO, JSONObject data, SheetTypeEnum sheetTypeEnum) throws XbbException {
        boolean newFlag = Objects.equals(validateDataDTO.getDataId(), null) || Objects.equals(validateDataDTO.getDataId(), BasicConstant.ZERO_LONG);
        //校验回/付款单金额不能为0（明细内金额不用校验为0）
        boolean checkAmountFlag = (validateDataDTO.getNonCheckAmount() == null || !validateDataDTO.getNonCheckAmount()) && newFlag;
        String msg;
        if (checkAmountFlag) {
            Double amount = FundUtil.getSheetAmountBySheetType(sheetTypeEnum, data);
            if (amount <= BasicConstant.ZERO) {
                if (SheetTypeEnum.isRed(sheetTypeEnum)) {
                    msg = I18nMessageUtil.getMessage(I18nStringConstant.RED_AMOUNT);
                } else {
                    msg = I18nMessageUtil.getMessage(I18nStringConstant.AMOUNT);
                }
                throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208034.getCode(), format(PaymentErrorCodeEnum.API_ERROR_208034.getMsg(), msg));
            }
        }
        //新增则校验收款日期、付款日期在31天内：仅支持31天至今
        if (newFlag) {
            String timeAttr = null;
            msg = "";
            Map<String, FieldAttrEntity> explainMap = validateDataDTO.getExplainMap();
            switch (sheetTypeEnum.getXbbRefTypeEnum()) {
                case OTHER_INCOME:
                    timeAttr = OtherIncomeEnum.INCOME_TIME.getAttr();
                    msg = OtherIncomeEnum.INCOME_TIME.getAttrName();
                    break;
                case OTHER_EXPENSE:
                    timeAttr = OtherExpenseEnum.EXPENSE_TIME.getAttr();
                    msg = OtherExpenseEnum.EXPENSE_TIME.getAttrName();
                    break;
                default:
                    break;
            }
            Long sheetTime = data.getLongValue(timeAttr);
            if (SheetTypeEnum.isRed(sheetTypeEnum)) {
                //红冲则直接强制使用“红冲日期”
                msg = SheetAssembleEnum.RedOther.OTHER_TIME.getName();
            } else if (Objects.nonNull(explainMap) && explainMap.containsKey(timeAttr)) {
                //非红冲，如果explainMap不为空，则使用模板内日期字段名称
                FieldAttrEntity fieldAttrEntity = explainMap.get(timeAttr);
                msg = fieldAttrEntity.getAttrName();
            }
            Long now = DateTimeUtil.getInt();
            if (sheetTime > now) {
                throw new XbbException(FundsSetErrorCodeEnum.API_ERROR_2500005.getCode(), format(FundsSetErrorCodeEnum.API_ERROR_2500005.getMsg(), msg));
            }
            Integer count = DateTimeUtil.lastConnect(sheetTime, now);
            if (count > TimeConstant.MONTH) {
                throw new XbbException(FundsSetErrorCodeEnum.API_ERROR_2500006.getCode(), format(FundsSetErrorCodeEnum.API_ERROR_2500006.getMsg(), TimeConstant.MONTH));
            }
        }
    }

    /**
     * 生日格式转换
     * 将前端传入的json对象格式转换成三个字段
     *
     * @param data                    前端传回的data数据
     * @param attr                    要格式化的字段attr
     * @param birthdayFlag      公历生日字段的隐藏字段attr
     * @param birthdayMmdd 阴历生日字段隐藏的字段attr
     * @throws XbbException 参数格式错误异常
     * @author chaoxiong.lei
     * @date 15:38 2019/1/21
     * @since v1.0
     **/
    public static void formatBirthday4Save(JSONObject data, String attr, String birthdayFlag,String birthdayMmdd) throws XbbException {
        if (data == null || attr == null || birthdayFlag == null) {
            return;
        }
        try {
            JSONObject jsonObject = data.getJSONObject(attr);
            if (jsonObject != null) {
                Integer isLunarBirthdayShown = jsonObject.getInteger(StringConstant.BIRTHDAY_FLAG);
                String birthday = jsonObject.getString(StringConstant.BIRTHDAY);
                data.put(attr, birthday);
                data.put(birthdayFlag, isLunarBirthdayShown);
                data.put(birthdayMmdd, DateTimeUtil.getString(DateTimeUtil.getDate(birthday, DateTimeUtil.SDFDate), DateTimeUtil.SDFMonthDay));
            }
        } catch (Exception e) {

        }
    }
    /**
     * 将前端传入的json对象格式转换成两个字段__TextCheck
     *
     * @param data       前端传回的data数据
     * @param attr       要格式化的字段attr
     * @param linkedAttr 格式化字段对应的隐藏字段
     * @throws XbbException 参数格式错误异常
     * @author feng.zheng
     * @date 15:38 2019/1/31
     * @since v1.0
     **/
    public static void formatTextCheck4Save(JSONObject data, String attr, String linkedAttr) throws XbbException {
        if (data == null || attr == null || linkedAttr == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }
        try {
            JSONObject jsonObject = data.getJSONObject(attr);
            if (jsonObject != null) {
                String value = jsonObject.getString(StringConstant.VALUE);
                Integer checked = jsonObject.getInteger(StringConstant.CHECKED);
                data.put(attr, value);
                data.put(linkedAttr, checked);
            }
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
    }

    /**
     * BOM单校验
     *
     * @param data
     * @param corpid
     * @throws XbbException 参数格式错误异常
     * @author long.rao
     * @date 2019-02-17 16:36
     */
    public static void dataCheckForSaas(JSONObject data, String corpid) throws XbbException {
        String version = FastJsonHelper.getStringFromFormData(data, BomBillEnum.VERSION.getAttr());
        String name = FastJsonHelper.getStringFromFormData(data, BomBillEnum.NAME.getAttr());

        if (name != null && name.length() > AttrLenthConstant.NAME_MAX_LENGTH) {
            throw new XbbException(BomErrorCodeEnum.API_ERROR_242039);
        }
        int maxVersionLength = 50;
        if (StringUtil.isEmpty(version)) {
            throw new XbbException(BomErrorCodeEnum.API_ERROR_242015);
        }
        if (version.length() > maxVersionLength) {
            throw new XbbException(BomErrorCodeEnum.API_ERROR_242040);
        }


//        // 成品校验
//        JSONArray productArray = saasSaveHelp.getProductArrayFromData(data, BomBillEnum.PRODUCT.getAttr());
//        if (productArray == null || productArray.size() == 0) {
//            throw new XbbException(ErrorCodeEnum.API_ERROR_242017);
//        }
//        // 一个BOM清单只有一个成品
//        if (productArray.size() > 1) {
//            throw new XbbException(ErrorCodeEnum.API_ERROR_242034);
//        }
//        Long productId = 0L;
//        for (int i = 0; i < productArray.size(); i++) {
//            JSONObject productObj = productArray.getJSONObject(i);
//            productId = productObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
//            ProductEntityExt productEntity = productModel.getByKey(productId, corpid);
//            if (productEntity == null) {
//                // 产品不存在
//                throw new XbbException(ErrorCodeEnum.API_ERROR_242021);
//            }
//            if (productEntity.getDel() == 1) {
//                // 产品已删除
//                throw new XbbException(ErrorCodeEnum.API_ERROR_242022);
//            }
//
//        }
//
//        // 物料产品校验
//        JSONArray materialProduct = saasSaveHelp.getProductArrayFromData(data, BomBillEnum.MATERIEL.getAttr());
//        if (materialProduct == null || materialProduct.size() == 0) {
//            throw new XbbException(ErrorCodeEnum.API_ERROR_242018);
//        }
//        for (int i = 0; i < materialProduct.size(); i++) {
//            JSONObject materielObj = materialProduct.getJSONObject(i);
//            Long materielProductId = materielObj.getLong("id");
//            ProductEntityExt productEntity = productModel.getByKey(materielProductId, corpid);
//            if (productEntity == null) {
//                // 产品不存在
//                throw new XbbException(ErrorCodeEnum.API_ERROR_242021);
//            }
//            if (productEntity.getDel() == 1) {
//                // 产品已删除
//                throw new XbbException(ErrorCodeEnum.API_ERROR_242022);
//            }
//            // 物料产品数量校验
//            String productNumStr = materielObj.getString("num");
//            if (!StringUtil.isDigital(productNumStr)) {
//                throw new XbbException(ErrorCodeEnum.API_ERROR_242028);
//            }
//            Double productNum = Double.valueOf(productNumStr);
//            if (productNum <= 0) {
//                throw new XbbException(ErrorCodeEnum.API_ERROR_242020);
//            }
//            // 物料损耗率校验
//            String attritionRate = materielObj.getString("attritionRate");
//            if (!StringUtil.isDigital(attritionRate)) {
//                throw new XbbException(ErrorCodeEnum.API_ERROR_242023);
//            }
//            if (Double.valueOf(attritionRate) < 0 || Double.valueOf(attritionRate) >= 100) {
//                throw new XbbException(ErrorCodeEnum.API_ERROR_242024);
//            }
//        }
//
//        if (isDefault != null && Objects.equals(isDefault, 1)) {
//            checkBomAndFinshedProduct(corpid, productId);
//        }
    }
    
    /**
     * 标签字段处理
     * @param data
     * @param explainMap
     * @throws XbbException
     */
    public static void dealLabelData(JSONObject data,  Map<String, FieldAttrEntity> explainMap) throws XbbException {
        // 标签处理
        String labelAttr;
        for (FieldAttrEntity value : explainMap.values()) {
            if (Objects.equals(value.getFieldType(), FieldTypeEnum.LABEL.getType())){
                labelAttr = value.getAttr();
                JSONArray stringLableData = getStringLableData(data, labelAttr);
                data.put(labelAttr, stringLableData);
                break;
            }
        }
    }

    /**
     * 返回labelId数组
     * 返回可能为null，获取之后需要进行非null判断
     *
     * @param data 表单数据
     * @param attr 要获取数据的key值
     * @throws XbbException 类型转换失败异常
     * @author chaoxiong.lei
     * @date 14:09 2019/1/23
     * @since v1.0
     **/
    public static JSONArray getStringLableData(JSONObject data, String attr) throws XbbException {
        JSONArray result = null;
        if (data == null || attr == null) {
            return result;
        }
        try {
            if (data.get(attr) == null) {
                return null;
            }
            JSONArray labelIds= new JSONArray();
            JSONArray jsonArray = data.getJSONArray(attr);
            try {
                List<LabelPojo> labelPojos = JSON.parseArray(jsonArray.toJSONString(), LabelPojo.class);
                for (LabelPojo item : labelPojos) {
                    labelIds.add(item.getId());
                }
            } catch (Exception e) {
                labelIds = data.getJSONArray(attr);
            }
            return labelIds;
        } catch (Exception e) {
            LOG.error("com.xbongbong.saas.help.SaasSaveHelp.getStringLableData出错",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
    }

    /**
     * 将前端传入的json对象格式转换成两个字段
     *
     * @param data                    前端传回的data数据
     * @param attr                    要格式化的字段attr
     * @param communicateBusinessType 格式化字段对应的隐藏字段
     * @throws XbbException 参数格式错误异常
     * @author feng.zheng
     * @date 15:38 2019/1/31
     * @since v1.0
     **/
    public static void formatCommunicateBusiness4Save(JSONObject data, String attr, String communicateBusinessType, String communicateBusinessLinkText) throws XbbException {
        if (data == null || attr == null || communicateBusinessType == null || communicateBusinessLinkText == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }
        try {
            JSONObject jsonObject = data.getJSONObject(attr);
            if (jsonObject != null) {
                Integer type = jsonObject.getInteger(StringConstant.BUSINESS_TYPE);
                String id = jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_ID);
                String name = jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_NAME);
                data.put(attr, id);
                data.put(communicateBusinessType, type);
                data.put(communicateBusinessLinkText, name);
            }
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
    }

    /**
     * 关联业务单选
     * 将前端传入的json对象格式转换成两个字段
     *
     * @param data       前端传回的data数据
     * @param attr       要格式化的字段attr
     * @param linkedAttr 格式化字段对应的隐藏字段
     * @throws XbbException 参数格式错误异常
     * @author chaoxiong.lei
     * @date 15:38 2019/1/21
     * @since v1.0
     **/
    public static void formatLinkBusiness4Save(JSONObject data, String attr, String linkedAttr, Integer fieldType) throws XbbException {
        if (data == null || attr == null || linkedAttr == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }
        try {
            JSONArray jsonArray = data.getJSONArray(attr);
            if (jsonArray != null && !jsonArray.isEmpty()) {
                List<String> idList = new ArrayList<>();
                List<String> nameList = new ArrayList<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    idList.add(jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_ID));
                    nameList.add(jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_NAME));
                }
                if (Objects.equals(FieldTypeEnum.LINK_BUSINESS_MULTI.getType(), fieldType)) {
                    // 鲁江：下拉多选不要用逗号或者竖线分割，存成array
                    data.put(attr,idList);
                    data.put(linkedAttr, nameList);
                } else {
                    if(idList.size() > BasicConstant.ZERO) {
                        data.put(attr, idList.get(BasicConstant.ZERO));
                    }else {
                        data.put(attr, null);
                    }
                    if(idList.size() > BasicConstant.ZERO) {
                        data.put(linkedAttr, nameList.get(BasicConstant.ZERO));
                    }else {
                        data.put(linkedAttr, null);
                    }
                }
            } else {
                data.put(attr, null);
                data.put(linkedAttr, null);
            }
        } catch (Exception e) {
            //   throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
    }

    /**
     * 保存时批次号必填校验
     * @param validateDataDTO 校验数据格式DTO
     * @throws XbbException
     */
    public static void batchSaveRequiredCheck(ValidateDataDTO validateDataDTO) throws XbbException{
        JSONObject data = validateDataDTO.getData();
        JSONArray productJsonArray = data.getJSONArray(InstockEnum.PRODUCT.getAttr());
        if(Objects.nonNull(productJsonArray)){
            if (!Objects.equals(XbbRefTypeEnum.REFUND.getCode(),validateDataDTO.getBusinessType())){
                batchRequiredCheck(productJsonArray, validateDataDTO.getBusinessType());
            }
            //退货退款特殊
            if(Objects.equals(XbbRefTypeEnum.REFUND.getCode(),validateDataDTO.getBusinessType())){
                batchRequiredCheck(productJsonArray , validateDataDTO.getBusinessType());
            }
            //装配单特殊处理  入库产品也要进行校验
            if (Objects.equals(validateDataDTO.getBusinessType(), XbbRefTypeEnum.ASSEMBLE.getCode())){
                JSONArray instockProduct = data.getJSONArray(AssembleEnum.IN_PRODUCTS.getAttr());
                batchRequiredCheck(instockProduct, validateDataDTO.getBusinessType());
            }
        }
    }

    /**
     * 单据保存前批次号 序列号 生产日期 保质期 到期日期校验
     * @param productJsonArray
     * @throws XbbException
     */
    private static void batchRequiredCheck(JSONArray productJsonArray ,Integer businessType)throws XbbException{

        //盘点单相同纬度产品导入校验
        //存放 产品Id_批次_生产日期_保质期 key的list
        Set<String> batchProductDateGuaranteePeriodSet = new HashSet<>();
        String key = null;
        // 保存必填校验
        for (int i = 0; i < productJsonArray.size(); i++) {
            JSONObject productData = productJsonArray.getJSONObject(i);
            //产品id
            String productId = productData.getString(ProductEnum.NAME.getAttr());
            // 批次号是否启用
            Integer enableBatchShelfLife = getIntegerOrDefaultFromFormData(productData, ProductEnum.ENABLE_BATCH_SHELF_LIFE.getSaasAttr(), 0);
            //序列号是否启用
            Integer enbleSeialnum = getIntegerOrDefaultFromFormData(productData, ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr(),0);
            // 保质期是否启用
            Integer shelfLifeDays = getIntegerOrDefaultFromFormData(productData, ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), 0);
            // 批次号
            String batch = productData.getString(SelectProductEnum.BATCH.getAttr());
            //   保质期  生产日期
            Long guaranteePeriod = FastJsonHelper.getLongOrDefaultFromFormData(productData,SelectProductEnum.GUARANTEE_PERIOD.getAttr(), null);
            Long productDate = FastJsonHelper.getLongOrDefaultFromFormData(productData, SelectProductEnum.PRODUCE_DATE.getAttr(), null);
            //盘点单 产品名称 批次号 保质期 生产日期完全一致的情况下不允许导入
            if (Objects.equals(XbbRefTypeEnum.INVENTORY.getCode(), businessType)) {
                key = productId + "_" + batch + "_" + productDate + "_" + guaranteePeriod;
                if (batchProductDateGuaranteePeriodSet.contains(key)) {
                    throw new XbbException(InstockErrorCodeEnum.API_ERROR_210043, String.format(InstockErrorCodeEnum.API_ERROR_210043.getMsg(), i + 1));
                }
                batchProductDateGuaranteePeriodSet.add(key);
            }
            //启用了序列号  装配单不校验
            if (StockConstant.SERIAL_TYPE_LIST.contains(businessType) && Objects.equals(BasicConstant.ONE,enbleSeialnum) && !Objects.equals(XbbRefTypeEnum.ASSEMBLE.getCode(),businessType)){
                Object seq = productData.get("seq");
                if (Objects.isNull(seq)){
                    throw new XbbException(InstockErrorCodeEnum.API_ERROR_210039, String.format(InstockErrorCodeEnum.API_ERROR_210039.getMsg(),i+1));
                }
            }
            if (BasicConstant.ONE.equals(enableBatchShelfLife)){
                // 启用批次号  校验批次号必填
                if (StringUtil.isEmpty(batch)){
                    throw new XbbException(InstockErrorCodeEnum.API_ERROR_210036, String.format(InstockErrorCodeEnum.API_ERROR_210036.getMsg(), i+1));
                }
            }else{
                // 未启用批次号  校验批次号不能填  过滤批次保质期字段
                // 过滤批次号字段
                productData.remove(SelectProductEnum.BATCH.getAttr());
            }
            //启用批次管理的前提下 才能启用保质期管理
            if (BasicConstant.ONE.equals(enableBatchShelfLife) && BasicConstant.ONE.equals(shelfLifeDays)){
                // 启用保质期  校验保质期，生产日期必填
                if (Objects.isNull(guaranteePeriod) || Objects.isNull(productDate)){
                    throw new XbbException(InstockErrorCodeEnum.API_ERROR_210037, String.format(InstockErrorCodeEnum.API_ERROR_210037.getMsg(), i+1));
                }
                //拼进到期日期字段
                productData.put(SelectProductEnum.EXPIRE_DATE.getAttr(), guaranteePeriod * 86400 + productDate );
//                //到期日期必须大于生产日期校验
//                if (Objects.nonNull(productDate) && Objects.nonNull(expireDate)){
//                    if (productDate > expireDate){
//                        throw new XbbException(ProductErrorCodeEnum.API_ERROR_205080);
//                    }
//                }
            }else{
                // 过滤掉保质期 生产日期，到期日期
                productData.remove(SelectProductEnum.PRODUCE_DATE.getAttr());
                productData.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
                productData.remove(SelectProductEnum.EXPIRE_DATE.getAttr());
            }
        }
    }
    /**
     * 关联业务单选
     * 将前端传入的json对象格式转换成两个字段
     *
     * @param data       前端传回的data数据
     * @param attr       要格式化的字段attr
     * @param linkedAttr 格式化字段对应的隐藏字段
     * @throws XbbException 参数格式错误异常
     * @author chaoxiong.lei
     * @date 15:38 2019/1/21
     * @since v1.0
     **/
    public static void formatLinkBusiness4SaveByArray(JSONObject data, String attr, String linkedAttr, Integer fieldType) throws XbbException {
        if (data == null || attr == null || linkedAttr == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }
        try {
            JSONArray jsonArray = data.getJSONArray(attr);
            if (jsonArray != null && !jsonArray.isEmpty()) {
                //StringBuilder id = new StringBuilder();
                //StringBuilder name = new StringBuilder();
                List<String> idList = new ArrayList<>();
                List<String> nameList = new ArrayList<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    idList.add(jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_ID));
                    nameList.add(jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_NAME));
                    //id.append(jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_ID)).append(StringConstant.COMMA);
                    //name.append(jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_NAME)).append(StringConstant.COMMA);
                }
                // 去掉最后的","号
                //String substringId = id.toString().substring(0, id.length() - 1);
                //String substringName = name.toString().substring(0, name.length() - 1);

                if (Objects.equals(FieldTypeEnum.LINK_BUSINESS_MULTI.getType(), fieldType)) {
                    // 鲁江：下拉多选不要用逗号或者竖线分割，存成array
                    //String[] substringIdArray = substringId.split(StringConstant.COMMA);
                    //String[] substringNameArray = substringName.split(StringConstant.COMMA);
                    data.put(attr,idList);
                    data.put(linkedAttr, nameList);
                } else {
                    if(idList.size() > BasicConstant.ZERO) {
                        data.put(attr, idList.get(BasicConstant.ZERO));
                    }else {
                        data.put(attr, null);
                    }
                    if(idList.size() > BasicConstant.ZERO) {
                        data.put(linkedAttr, nameList.get(BasicConstant.ZERO));
                    }else {
                        data.put(linkedAttr, null);
                    }
                }
            } else {
                data.put(attr, null);
                data.put(linkedAttr, null);
            }

        } catch (Exception e) {
            //   throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
    }

    /**
     * 根据关联id 获取实体
     * @param idAttr id attr
     * @param noAttr 编号attr
     * @param map id 对应编号map
     *
     */
    public static void commonGetRefEntity(String idAttr,String noAttr,Map<Long,String> map,JSONObject data){
        JSONArray refId = data.getJSONArray(idAttr);
        JSONArray refNo = data.getJSONArray(noAttr);
        for(int i=0;i < refId.size();i++){
            Long id = refId.getLong(i);
            String no = refNo.getString(i);
            map.put(id,no);
        }
    }

    /**
     * 将前端传入的产品数组转换成id数组
     *
     * @param data       前端传回的data数据
     * @param attr       要格式化的字段attr
     * @throws XbbException 参数格式错误异常
     * @author haibin.zhang
     * @date 15:38 2019/10/15
     * @since v1.0
     **/
    public static JSONArray formatSelectProduct4Save2(JSONObject data, String attr) throws XbbException {
        if (data == null || attr == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }
        try {
            JSONArray productArray = data.getJSONArray(attr);
            if (productArray == null) {
                return new JSONArray();
            }
            Set<Long> ids = new HashSet<>();
            for (int i = 0; i < productArray.size(); i++) {
                JSONObject jsonObject = productArray.getJSONObject(i);
                if (jsonObject != null) {
                    Long productId = jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr());
                    ids.add(productId);
                }
            }
            data.put(attr, ids.toArray());
            return productArray;
        } catch (Exception e) {
            data.put(attr, new JSONArray());
            return new JSONArray();
        }
    }

    public static String handlePayMethod4Distributor(String platform, JSONObject data, String sheetType, Integer distributorMark) {
        //经销商端platform为INTERNAL，经销商类型回款单，且不是经销商端调用
        boolean flag = Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode()) && !Objects.equals(platform, PlatFormEnum.INTERNAL.getValue());
        String payMethod = data.getString(PaymentSheetDistributorEnum.PAY_METHOD.getAttr());
        if (flag && StringUtil.isEmpty(payMethod)) {
            payMethod = SheetTypeEnum.getDefaultPayMethod4Distributor(sheetType);
            data.put(PaymentSheetDistributorEnum.PAY_METHOD.getAttr(), payMethod);
            return payMethod;
        }
        return payMethod;
    }
}
